from selenium import webdriver
from urllib.parse import urlparse
import time
import requests
import json
import base64
import urllib
from selenium.webdriver import ActionChains



# 建立浏览器对象


browser = webdriver.Chrome()
#
# #打开网址
browser.get('http://localhost:8080/login')
#
time.sleep(3)
#
# # 选择元素
myimg = browser.find_element_by_xpath('/html/body/div[1]/div/section/div/table/tr[4]/td[2]/img')
print(myimg)

# myimg = browser.find_element_by_xpath('//*[@id="app"]/div/section/div/table/tr[4]/td[2]/img')
# print(myimg)


#
#
# # 截取屏幕
myimg.screenshot('code1.png')
# browser.get_screenshot_as_file('register.png')
#
# browser.close()

# 请求百度接口
res = requests.get('https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=3xIXz3mqYXt0meOPxaVPmThq&client_secret=B5GrwiN0PUEXCDODyEf5gFGLMr7oO5cb')
#
#
# # 转码
res = json.loads(str(res.text))
token = res['access_token']

#
# # 识别图像
url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + token

# 构造头部

header = {'Content-Type':'application/x-www-form-urlencoded'}

# 构造图片
img = open('./code1.png', 'rb')
temp_img = img.read()
# img.close()

# 构建参数
data = {'image':base64.b64encode(temp_img)}
# 编码
data = urllib.parse.urlencode(data)

# 发送请求
res = requests.post(url=url,data=data,headers=header)


# js转化
code = json.loads(res.text)



# 模拟操作 提交信息

code = code['words_result'][0]['words']

browser.find_element_by_xpath('/html/body/div[1]/div/section/div/table/tr[1]/td[2]/input').send_keys('小王')

browser.find_element_by_xpath('/html/body/div[1]/div/section/div/table/tr[2]/td[2]/input').send_keys('1234')

#填入验证码
browser.find_element_by_xpath('/html/body/div[1]/div/section/div/table/tr[3]/td[2]/input').send_keys(code.strip().replace(' ',''))

#进行拖动操作
button = browser.find_element_by_class_name('dv_handler')
print(button)
#声明动作实例
action = ActionChains(browser)
#点击并且按住
action.click_and_hold(button).perform()
action.reset_actions()
#实际拖动像素和轨迹长度是有出入的
action.move_by_offset(280,0).perform()



#登录按钮 xpath方法
# browser.find_element_by_xpath('/html/body/div[1]/div/section/div/table/tr[5]/td[2]/button[1]/span').click()

#点击登录按钮 name方法
browser.find_element_by_class_name('h-btn').click()

# 停留5秒
time.sleep(5)
# 退出
browser.close()
